<template>
  <div>
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="待支付" name="pending-payment"></el-tab-pane>
      <el-tab-pane label="未发货" name="not-shipped"></el-tab-pane>
      <el-tab-pane label="已发货" name="shipped"></el-tab-pane>
      <el-tab-pane label="待评价" name="pending-review"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
    </el-tabs>
、      <h2>{{ activeTabLabel }}</h2>
      <div v-if="activeTab === 'pending-payment'">
        <div v-if="pendingOrders.length === 0" class="no-orders">
          没有待支付的订单。
        </div>
        <div v-else>
          <ul class="order-list">
            <li
              v-for="order in pendingOrders"
              :key="order.id"
              class="order-item"
            >
              <div class="order-header">
                <span class="order-id">订单号: {{ order.id }}</span>
                <span class="order-total"
                  >总价: {{ order.total_price }} 元</span
                >
              </div>
              <div class="order-address">
                <span>收货人: {{ order.address.name }}</span>
                <span>地址: {{ order.address.address }}</span>
              </div>
              <ul class="item-list">
                <li
                  v-for="item in productsList"
                  :key="item.id"
                  class="item"
                  v-if="
                    order.order_items.some(
                      (orderItem) => orderItem.product_id === item.id
                    )
                  "
                >
                  <span class="item-name">商品名称: {{ item.shop_name }}</span>
                  <span class="item-quantity"
                    >数量:
                    {{
                      order.order_items.find(
                        (orderItem) => orderItem.product_id === item.id
                      ).quantity
                    }}</span
                  >
                  <span class="item-price">单价: {{ item.shop_price }} 元</span>
                  <img
                    :src="getImageUrl(item.shop_img)"
                    alt="商品图片"
                    class="item-image"
                  />
                  <el-button type="text" @click="selectProduct(item.id)"
                    ></el-button
                  >
                </li>
              </ul>
              <el-button
                type="primary"
                @click="payOrder(order.id)"
                class="pay-button"
                >支付订单</el-button
              >
            </li>
          </ul>
        </div>
      </div>
      <div v-if="activeTab === 'not-shipped'">
        <div v-if="notShippedOrders.length === 0" class="no-orders">
          没有未发货的订单。
        </div>
        <div v-else>
          <ul class="order-list">
            <li
              v-for="order in notShippedOrders"
              :key="order.id"
              class="order-item"
            >
              <div class="order-header">
                <span class="order-id">订单号: {{ order.id }}</span>
                <span class="order-total"
                  >总价: {{ order.total_price }} 元</span
                >
              </div>
              <div class="order-address">
                <span>收货人: {{ order.address.name }}</span>
                <span>地址: {{ order.address.address }}</span>
              </div>
              <ul class="item-list">
                <li
                  v-for="item in productsList"
                  :key="item.id"
                  class="item"
                  v-if="
                    order.order_items.some(
                      (orderItem) => orderItem.product_id === item.id
                    )
                  "
                >
                  <span class="item-name">商品名称: {{ item.shop_name }}</span>
                  <span class="item-quantity"
                    >数量:
                    {{
                      order.order_items.find(
                        (orderItem) => orderItem.product_id === item.id
                      ).quantity
                    }}</span
                  >
                  <span class="item-price">单价: {{ item.shop_price }} 元</span>
                  <img
                    :src="getImageUrl(item.shop_img)"
                    alt="商品图片"
                    class="item-image"
                  />
                  <el-button type="text" @click="selectProduct(item.id)"
                    ></el-button
                  >
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
      <div v-if="activeTab === 'shipped'">
        <div v-if="shippedOrders.length === 0" class="no-orders">
          没有已发货的订单。
        </div>
        <div v-else>
          <ul class="order-list">
            <li
              v-for="order in shippedOrders"
              :key="order.id"
              class="order-item"
            >
              <div class="order-header">
                <span class="order-id">订单号: {{ order.id }}</span>
                <span class="order-total"
                  >总价: {{ order.total_price }} 元</span
                >
              </div>
              <div class="order-address">
                <span>收货人: {{ order.address.name }}</span>
                <span>地址: {{ order.address.address }}</span>
              </div>
              <ul class="item-list">
                <li
                  v-for="item in productsList"
                  :key="item.id"
                  class="item"
                  v-if="
                    order.order_items.some(
                      (orderItem) => orderItem.product_id === item.id
                    )
                  "
                >
                  <span class="item-name">商品名称: {{ item.shop_name }}</span>
                  <span class="item-quantity"
                    >数量:
                    {{
                      order.order_items.find(
                        (orderItem) => orderItem.product_id === item.id
                      ).quantity
                    }}</span
                  >
                  <span class="item-price">单价: {{ item.shop_price }} 元</span>
                  <img
                    :src="getImageUrl(item.shop_img)"
                    alt="商品图片"
                    class="item-image"
                  />
                  <el-button type="text" @click="selectProduct(item.id)"
                    ></el-button
                  >
                </li>
              </ul>
              <el-button
                type="primary"
                @click="confirmReceipt(order.id)"
                class="confirm-button"
                >确认收货</el-button
              >
            </li>
          </ul>
        </div>
      </div>
      <div v-if="activeTab === 'pending-review'">
        <div v-if="pendingReviewOrders.length === 0" class="no-orders">
          没有待评价的订单。
        </div>
        <div v-else>
          <ul class="order-list">
            <li
              v-for="order in pendingReviewOrders"
              :key="order.id"
              class="order-item"
            >
              <div class="order-header">
                <span class="order-id">订单号: {{ order.id }}</span>
                <span class="order-total"
                  >总价: {{ order.total_price }} 元</span
                >
              </div>
              <div class="order-address">
                <span>收货人: {{ order.address.name }}</span>
                <span>地址: {{ order.address.address }}</span>
              </div>
              <ul class="item-list">
                <li
                  v-for="item in productsList"
                  :key="item.id"
                  class="item"
                  v-if="
                    order.order_items.some(
                      (orderItem) => orderItem.product_id === item.id
                    )
                  "
                >
                  <span class="item-name">商品名称: {{ item.shop_name }}</span>
                  <span class="item-quantity"
                    >数量:
                    {{
                      order.order_items.find(
                        (orderItem) => orderItem.product_id === item.id
                      ).quantity
                    }}</span
                  >
                  <span class="item-price">单价: {{ item.shop_price }} 元</span>
                  <img
                    :src="getImageUrl(item.shop_img)"
                    alt="商品图片"
                    class="item-image"
                  />
                  <el-button
                    type="primary"
                    @click="openRatingModal(item.id, order.id)"
                    class="review-button"
                    >去评价</el-button
                  >
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
      <div v-if="activeTab === 'completed'">
        <div v-if="completedOrders.length === 0" class="no-orders">
          没有已完成的订单。
        </div>
        <div v-else>
          <ul class="order-list">
            <li
              v-for="order in completedOrders"
              :key="order.id"
              class="order-item"
            >
              <div class="order-header">
                <span class="order-id">订单号: {{ order.id }}</span>
                <span class="order-total"
                  >总价: {{ order.total_price }} 元</span
                >
              </div>
              <div class="order-address">
                <span>收货人: {{ order.address.name }}</span>
                <span>地址: {{ order.address.address }}</span>
              </div>
              <ul class="item-list">
                <li
                  v-for="item in productsList"
                  :key="item.id"
                  class="item"
                  v-if="
                    order.order_items.some(
                      (orderItem) => orderItem.product_id === item.id
                    )
                  "
                >
                  <span class="item-name">商品名称: {{ item.shop_name }}</span>
                  <span class="item-quantity"
                    >数量:
                    {{
                      order.order_items.find(
                        (orderItem) => orderItem.product_id === item.id
                      ).quantity
                    }}</span
                  >
                  <span class="item-price">单价: {{ item.shop_price }} 元</span>
                  <img
                    :src="getImageUrl(item.shop_img)"
                    alt="商品图片"
                    class="item-image"
                  />
                  
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </div>

 



      <el-dialog title="商品详情" :visible.sync="productDetailsDialogVisible">
<div v-if="selectedProduct">
  <p>评价: {{ selectedProduct.data[0].comment }}</p>
  <el-rate v-model="selectedProduct.data[0].rating" disabled></el-rate>
</div>
<span slot="footer" class="dialog-footer">
  <el-button @click="productDetailsDialogVisible = false">取 消</el-button>
</span>
</el-dialog>

      <el-dialog title="添加评价" :visible.sync="ratingDialogVisible">
        <el-form :model="ratingForm">
          <el-form-item label="评价内容">
            <el-input v-model="ratingForm.comment"></el-input>
          </el-form-item>
          </el-form-item>
          <el-form-item label="评分">
            <el-rate v-model="ratingForm.rating"></el-rate>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRating">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      activeTab: "pending-payment",
      pendingOrders: [],
      notShippedOrders: [],
      shippedOrders: [],
      pendingReviewOrders: [],
      completedOrders: [],
      selectedProduct: null,
      productsList: [],
      ratingDialogVisible: false,
      productDetailsDialogVisible: false,
      ratingForm: {
        comment: "",
        username: localStorage.getItem("userName") || "",
        rating: 0,
        product_id: null,
        order_id: null,
      },
    };
  },
  computed: {
    activeTabLabel() {
      switch (this.activeTab) {
        case "pending-payment":
          return "待支付";
        case "not-shipped":
          return "未发货";
        case "shipped":
          return "已发货";
        case "pending-review":
          return "待评价";
        case "completed":
          return "已完成";
      }
    },
  },
  methods: {
    handleTabClick(tab) {
      this.fetchOrders();
    },
    fetchOrders() {
      const customer_id = localStorage.getItem("userId");
      if (!customer_id) {
        this.$message.error("用户未登录或ID不存在");
        return;
      }
      axios
        .get("/orders", { params: { customer_id: customer_id } })
        .then((response) => {
          if (response.data.code === 200) {
            console.log("order获得的数据", response.data.data);
            const orders = response.data.data;
            this.pendingOrders = orders.filter(
              (order) => order.status === "待付款"
            );
            this.notShippedOrders = orders.filter(
              (order) => order.status === "待发货"
            );
            this.shippedOrders = orders.filter(
              (order) => order.status === "已发货"
            );
            this.pendingReviewOrders = orders.filter(
              (order) => order.status === "待评价"
            );
            this.completedOrders = orders.filter(
              (order) => order.status === "已完成"
            );
            this.fetchProductDetails();
            this.fetchAddresses(orders); // 新增调用地址的函数
          } else {
            this.$message.error("获取订单失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          this.$message.error("获取订单失败，请重试。");
        });
    },
    fetchAddresses(orders) {
      const addressIds = orders.map((order) => order.address); // 假设每个订单都有 address_id
      const uniqueAddressIds = [...new Set(addressIds)];
      uniqueAddressIds.forEach((id) => {
        axios
          .get(`/Address/GetByid`, { params: { id: id } })
          .then((response) => {
            if (response.data.code === 200) {
              console.log("addressgetbyid返回的数据", response.data.data);
              console.log("现在的", id);
              const addressData = response.data.data;
              // 将地址信息添加到对应的订单中
              orders.forEach((order) => {
                if (order.address === id) {
                  order.address = addressData[0]; // 假设返回的地址数据是数组
                }
              });
            } else {
              console.error("获取地址失败:", response.data.msg);
            }
          })
          .catch((error) => {
            console.error("获取地址失败:", error);
          });
      });
    },
    fetchProductDetails() {
      const productIds = this.pendingOrders.flatMap((order) =>
        order.order_items.map((item) => item.product_id)
      );
      const uniqueProductIds = [...new Set(productIds)];
      axios
        .get("/GetProductsList", {})
        .then((response) => {
          if (response.data.code === 200) {
            this.productsList = response.data.data;
          } else {
            console.error("获取商店数据失败:", response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取商店数据失败:", error);
        });
    },
    getImageUrl(base64String) {
      return `data:image/jpeg;base64,${base64String}`;
    },
    selectProduct(productId) {
      this.selectedProduct = this.productsList.find(
        (product) => product.id === productId
      );
    },
    payOrder(orderId) {
      console.log("支付订单:", orderId);
      axios
        .put(`/orders/${orderId}/status?status=2`)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("支付成功！感谢您的购买。");
            this.fetchOrders(); // 重新获取订单以更新状态
          } else {
            this.$message.error("支付失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("更新订单状态失败:", error);
          this.$message.error("支付失败，请重试。");
        });
    },
    confirmReceipt(orderId) {
      console.log("确认收货:", orderId);
      axios
        .put(`/orders/${orderId}/status?status=4`)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("确认收货成功！");
            this.fetchOrders(); // 重新获取订单以更新状态
          } else {
            this.$message.error("确认收货失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("确认收货失败:", error);
          this.$message.error("确认收货失败，请重试。");
        });
    },
    openRatingModal(productId, orderId) {
      this.ratingForm.product_id = productId;
      this.ratingForm.order_id = orderId;
      this.ratingDialogVisible = true;
    },
    submitRating() {
      axios
        .post("/AddRatting", this.ratingForm)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("评价添加成功！");
            this.updateOrderStatus(this.ratingForm.order_id);
            this.ratingDialogVisible = false;
            this.fetchOrders(); // Refresh orders to reflect changes
          } else {
            this.$message.error("评价添加失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          this.$message.error("评价添加失败，请重试。");
        });
    },
    updateOrderStatus(orderId) {
      axios
        .put(`/orders/${orderId}/status?status=5`)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("订单状态更新成功！");
          } else {
            this.$message.error("订单状态更新失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          this.$message.error("更新订单状态失败，请重试。");
        });
    },
    viewProductDetails(productId) {
  const product = this.productsList.find((item) => item.id === productId);
  if (product) {
    this.selectedProduct = product; // 设置选中的商品
    this.productDetailsDialogVisible = true; // 显示商品详情对话框
    // 获取商品的评价信息
    axios
      .get("/GetRattingById", { params: { product_id: productId } })
      .then((response) => {
        if (response.data.code === 200) {
          this.selectedProduct.data = response.data.data; // 确保将评价数据存储在 selectedProduct 中
        } else {
          this.$message.error("获取商品详情失败: " + response.data.msg);
        }
      })
      .catch((error) => {
        console.error("获取商品详情失败:", error);
        this.$message.error("获取商品详情失败，请重试。");
      });
  } else {
    this.$message.error("未找到商品详情");
  }
},
  },
  mounted() {
    this.fetchOrders();
  },
};
</script>

<style scoped>
.order-content {
  margin-top: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h2 {
  font-size: 24px;
  margin-bottom: 10px;
}
.order-list {
  list-style-type: none;
  padding: 0;
}
.order-item {
  background-color: #fff;
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}
.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.order-id {
  font-weight: bold;
}
.order-total {
  color: #ff5722; /* 价格颜色 */
}
.order-address {
  margin-bottom: 10px; /* 地址信息的样式 */
}
.item-list {
  list-style-type: none;
  padding: 0;
}
.item {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
  border-bottom: 1px solid #e0e0e0;
}
.item-name {
  flex: 1;
}
.item-quantity,
.item-price {
  margin-left: 10px;
}
.item-image {
  max-width: 50px; /* 设置图片宽度 */
  height: auto;
  margin-left: 10px; /* 图片与文本之间的间距 */
}
.no-orders {
  color: #999;
  font-style: italic;
}
.pay-button {
  margin-top: 10px;
}
.confirm-button {
  margin-top: 10px;
}
.review-button {
  margin-top: 10px; /* 去评价按钮的样式 */
}
</style>
